<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="题目分类" prop="questionClassification">
        <el-select v-model="queryParams.questionClassification" placeholder="请选择题目类型" clearable size="small">
          <el-option v-for="dict in dict.type.question_classification"
                     :key="dict.value"
                     :label="dict.label"
                     :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题干" prop="questionTitle">
        <el-input v-model="queryParams.questionTitle"
                  placeholder="请输入题干"
                  clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary"
                   plain
                   icon="el-icon-plus"
                   size="mini"
                   @click="handleAdd"
                   v-hasPermi="['system:question:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success"
                   plain
                   icon="el-icon-edit"
                   size="mini"
                   :disabled="single"
                   @click="handleUpdate"
                   v-hasPermi="['system:question:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger"
                   plain
                   icon="el-icon-delete"
                   size="mini"
                   :disabled="multiple"
                   @click="handleDelete" v-hasPermi="['system:question:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning"
                   plain
                   icon="el-icon-download"
                   size="mini"
                   @click="handleExport"
                   v-hasPermi="['system:question:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" prop="id"/>
      <el-table-column label="题目类型" align="center" prop="questionType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.question_type" :value="scope.row.questionType"/>
        </template>
      </el-table-column>
      <el-table-column label="题目属性" align="center" prop="questionClassification">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.question_classification" :value="scope.row.questionClassification"/>
        </template>
      </el-table-column>
      <el-table-column label="题目标题" align="center" prop="questionTitle" min-width="200">
        <template slot-scope="scope">
          {{ formatQuestionTitle(scope.row.questionTitle) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="showQuestion1(scope.row)"
                     v-hasPermi="['system:question:edit']">预览
          </el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:question:edit']">修改
          </el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-delete"
                     @click="handleDelete(scope.row)"
                     v-hasPermi="['system:question:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改题目信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="题目类型" prop="questionType">
          <el-select v-model="form.questionType" placeholder="请选择题目类型" disabled clearable size="small">
            <el-option v-for="dict in dict.type.question_type"
                       :key="dict.value"
                       :label="dict.label"
                       :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题目属性" prop="questionClassification">
          <el-select v-model="form.questionClassification" placeholder="请选择题目属性" clearable size="small">
            <el-option v-for="dict in dict.type.question_classification"
                       :key="dict.value"
                       :label="dict.label"
                       :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题目标题" prop="questionTitle">
          <el-input v-model="form.questionTitle" @focus="inputClick(form,'title')" placeholder="请输入题干"/>
        </el-form-item>
        <el-form-item label="选项：" required>
          <el-form-item :label="item.prefix" :key="item.prefix" v-for="(item,index) in form.optionJson" label-width="50px" class="question-item-label">
            <el-input v-model="item.prefix" style="width:50px;"/>
            <el-input v-model="item.content" class="question-item-content-input"/>
            <el-input v-model="item.score" style="width:50px;margin-left: 10px"/>
            <el-button type="danger" size="mini" class="question-item-remove" icon="el-icon-delete" @click="questionItemRemove(index)"></el-button>
          </el-form-item>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="showQuestion">预览</el-button>
          <el-button type="success" @click="questionItemAdd">添加选项</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 富文本编辑器 -->
    <el-dialog :visible.sync="richEditor.dialogVisible" append-to-body :close-on-click-modal="false"
               style="width: 100%;height: 100%" :show-close="false" center>
      <Editor v-model="form.questionTitle" :min-height="492"/>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="richEditor.dialogVisible = false">确 定</el-button>
        <el-button @click="richEditor.dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 预览题目信息对话框 -->
    <el-dialog :visible.sync="questionShow.dialog" style="width: 100%;height: 100%">
      <QuestionShow :qType="questionShow.qType" :question="questionShow.question" :qLoading="questionShow.loading"/>
    </el-dialog>
  </div>
</template>

<script>
import Editor from '@/components/Editor'
import QuestionShow from '@/views/system/question/components/Show'
import {addQuestion, delQuestion, getQuestion, listQuestion, updateQuestion} from "@/api/system/question"

export default {
  name: "Single",
  components: {
    Editor, QuestionShow
  },
  dicts: ['question_type', 'question_classification'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题目信息表格数据
      questionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        questionType: "multiple",
        questionClassification: null,
        questionTitle: null,
        optionJson: null,
        correctJson: null,
        score: null,
      },
      richEditor: {
        dialogVisible: false,
        object: null,
        parameterName: '',
        instance: null
      },
      questionShow: {
        qType: "single",
        dialog: false,
        question: null,
        loading: false
      },
      // 表单参数
      form: {
        questionType: "multiple",
        correctJson: [],
        optionJson: [
          {prefix: 'A', content: '',score : "0"},
          {prefix: 'B', content: '',score : "0"},
          {prefix: 'C', content: '',score : "0"},
          {prefix: 'D', content: '',score : "0"}
        ],
      },
      // 表单校验
      rules: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询题目信息列表 */
    getList() {
      this.loading = true
      listQuestion(this.queryParams).then(response => {
        this.questionList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        questionType: "multiple",
        questionClassification: null,
        questionTitle: null,
        optionJson: [
          {prefix: 'A', content: '',score : "0"},
          {prefix: 'B', content: '',score : "0"},
          {prefix: 'C', content: '',score : "0"},
          {prefix: 'D', content: '',score : "0"}
        ],
        correctJson: [],
        score: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加题目信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getQuestion(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改题目信息"
        this.form.correct = this.form.correctJson[0]
        console.log(this.form)
      })
    },
    showQuestion() {
      this.questionShow.dialog = true
      this.questionShow.qType = this.form.questionType
      this.questionShow.question = this.form
    },
    showQuestion1(row) {
      this.questionShow.dialog = true
      this.questionShow.loading = true
      this.questionShow.qType = row.questionType
      this.questionShow.question = row
      this.questionShow.loading = false
    },
    inputClick(object, parameterName) {
      this.richEditor.object = object
      this.richEditor.parameterName = parameterName
      this.richEditor.dialogVisible = true
    },
    questionItemRemove(index) {
      this.form.optionJson.splice(index, 1)
    },
    questionItemAdd() {
      let items = this.form.optionJson
      let newLastPrefix
      if (items.length > 0) {
        let last = items[items.length - 1]
        newLastPrefix = String.fromCharCode(last.prefix.charCodeAt() + 1)
      } else {
        newLastPrefix = 'A'
      }
      items.push({id: null, prefix: newLastPrefix, content: ''})
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateQuestion(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addQuestion(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除题目信息编号为"' + ids + '"的数据项？').then(function () {
        return delQuestion(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/question/export', {
        ...this.queryParams
      }, `question_${new Date().getTime()}.xlsx`)
    },
    // ==================== 富文本处理方法 ====================

    /**
     * 去除HTML标签，保留纯文本
     */
    stripHtmlTags(htmlString) {
      if (!htmlString) return ''

      // 创建一个临时的div元素来解析HTML
      const tempDiv = document.createElement('div')
      tempDiv.innerHTML = htmlString

      // 获取纯文本内容
      let textContent = tempDiv.textContent || tempDiv.innerText || ''

      // 清理多余的空白字符
      textContent = textContent.replace(/\s+/g, ' ').trim()

      return textContent
    },

    /**
     * 格式化题目标题显示（限制长度）
     */
    formatQuestionTitle(htmlString) {
      if (!htmlString) return ''

      // 先去除HTML标签
      let plainText = this.stripHtmlTags(htmlString)

      // 限制显示长度，超出部分用省略号表示
      const maxLength = 50
      if (plainText.length > maxLength) {
        plainText = plainText.substring(0, maxLength) + '...'
      }

      return plainText
    }
  }
}
</script>

<style scoped>
.question-item-label {
  margin-top: 10px;
  margin-bottom: 10px !important;
}
</style>
